<?php
namespace app\api\controller;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

class QQMail {
    private $mail;
    private $config;

    public function __construct($config = []) {
        $this->config = array_merge([
            'host' => 'smtp.qq.com',
            'port' => 465,
            'encryption' => 'ssl',
            'username' => '309913834@qq.com',
            'password' => 'gtmtppbcslrqbjeg', // QQ邮箱授权码
            'sender_name' => '合创成',
            'timeout' => 30,
            'debug' => true
        ], $config);

        $this->initializeMailer();
    }

    private function initializeMailer() {
        $this->mail = new PHPMailer(true);

        try {
            // 服务器配置
            $this->mail->isSMTP();
            $this->mail->Host = $this->config['host'];
            $this->mail->SMTPAuth = true;
            $this->mail->Username = $this->config['username'];
            $this->mail->Password = $this->config['password'];
            $this->mail->SMTPSecure = $this->config['encryption'];
            $this->mail->Port = $this->config['port'];

            // 连接设置
            $this->mail->Timeout = $this->config['timeout'];
            $this->mail->SMTPKeepAlive = true;

            // SSL选项
            $this->mail->SMTPOptions = [
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                ]
            ];

            // 调试模式
            if ($this->config['debug']) {
                $this->mail->SMTPDebug = SMTP::DEBUG_SERVER;
            }

            // 编码设置
            $this->mail->CharSet = 'UTF-8';
            $this->mail->Encoding = 'base64';

            // 发件人配置
            $this->mail->setFrom($this->config['username'], $this->config['sender_name']);
            $this->mail->isHTML(false);

        } catch (Exception $e) {
            throw new Exception('邮件初始化失败: ' . $e->getMessage());
        }
    }

    /**
     * 发送验证码
     */
    public function sendVerificationCode($email, $code, $subject = '验证码通知') {
        try {
            // 收件人
            $this->mail->clearAddresses();
            $this->mail->addAddress($email);

            // 邮件内容
            $this->mail->Subject = $subject;
            $this->mail->Body = $this->getVerificationTemplate($code);
            $this->mail->AltBody = "您的验证码是：{$code}，有效期为10分钟。";

            if ($this->mail->send()) {
                return [
                    'success' => true,
                    'message' => '验证码发送成功'
                ];
            } else {
                throw new Exception('发送失败');
            }

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => '邮件发送失败: ' . $e->getMessage()
            ];
        }
    }

    /**
     * 发送普通邮件
     */
    public function sendEmail($to, $subject, $body, $altBody = '') {
        try {
            $this->mail->clearAddresses();
            $this->mail->addAddress($to);

            $this->mail->Subject = $subject;
            $this->mail->Body = $body;
            $this->mail->AltBody = $altBody ?: strip_tags($body);

            return $this->mail->send();

        } catch (Exception $e) {
            throw new Exception('邮件发送失败: ' . $e->getMessage());
        }
    }

    /**
     * 验证码邮件模板
     */
    private function getVerificationTemplate($code) {
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='utf-8'>
            <style>
                body { 
                    font-family: 'Microsoft YaHei', Arial, sans-serif; 
                    background-color: #f4f4f4; 
                    padding: 20px; 
                    margin: 0;
                }
                .container { 
                    max-width: 600px; 
                    margin: 0 auto; 
                    background: white; 
                    padding: 30px; 
                    border-radius: 10px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                }
                .header { 
                    text-align: center; 
                    border-bottom: 2px solid #12B7F5; 
                    padding-bottom: 20px;
                    margin-bottom: 20px;
                }
                .code { 
                    font-size: 32px; 
                    font-weight: bold; 
                    color: #12B7F5; 
                    text-align: center; 
                    margin: 30px 0;
                    padding: 15px;
                    background: #f8f9fa;
                    border-radius: 5px;
                    letter-spacing: 5px;
                }
                .footer { 
                    margin-top: 30px; 
                    font-size: 12px; 
                    color: #666; 
                    border-top: 1px solid #eee;
                    padding-top: 20px;
                }
                .warning {
                    color: #e74c3c;
                    font-weight: bold;
                }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2 style='color: #12B7F5; margin: 0;'>邮箱验证</h2>
                </div>
                
                <p>您好！</p>
                <p>您正在尝试进行邮箱验证，请使用以下验证码：</p>
                
                <div class='code'>{$code}</div>
                
                <p>验证码有效期为 <strong class='warning'>10分钟</strong>，请及时使用。</p>
                <p class='warning'>如果这不是您本人的操作，请立即忽略此邮件。</p>
                
                <div class='footer'>
                    <p>此邮件由系统自动发送，请勿回复。</p>
                    <p>如有问题，请联系客服。</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }
}